package services;

import dao.DeptInfo_Repository;
import models.DatabaseExecutionContext;
import models.DeptInfo_T_Entity;
import play.db.jpa.JPAApi;

import javax.inject.Inject;
import javax.persistence.Query;
import java.util.List;
import java.util.concurrent.CompletionStage;

import static java.util.concurrent.CompletableFuture.supplyAsync;


/**
 * Provide JPA operations running inside of a thread pool sized to the connection pool
 */
public class DeptInfo_Repository_JPA implements DeptInfo_Repository {

    private final JPAApi jpaApi;
    private final DatabaseExecutionContext executionContext;

    @Inject
    public DeptInfo_Repository_JPA(JPAApi jpaApi, DatabaseExecutionContext executionContext) {
        this.jpaApi = jpaApi;
        this.executionContext = executionContext;
    }

    @Override
    public CompletionStage<DeptInfo_T_Entity> getDeptByID (Integer DeptID)
    {
    	return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
            	Query query = entityManager.createQuery("select d from DeptInfo_T_Entity d where d.fdDeptId = :DeptID ", DeptInfo_T_Entity.class).setParameter("DeptID", DeptID);
            	DeptInfo_T_Entity _tDeptInfoEntity = new DeptInfo_T_Entity();
                if(query.getResultList().size() > 0)	
                {
                	_tDeptInfoEntity = (DeptInfo_T_Entity)query.getResultList().get(0);
                }
                else
                {
                	// 单位不存在等“异常”情况，仍然以结构返回。但返回为0
                	_tDeptInfoEntity.setFdDeptId(0);
                }
                
                return _tDeptInfoEntity;
            });
        }, executionContext);    	
    }
    
    @Override
    public CompletionStage<List<DeptInfo_T_Entity>> getDeptList ()
    {
    	return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
            	return entityManager.createQuery("select d from DeptInfo_T_Entity d", DeptInfo_T_Entity.class).getResultList();
            });
        }, executionContext);    	
    }

    //湛江有，上海没有
    @SuppressWarnings("unchecked")
    @Override
    public CompletionStage<List<DeptInfo_T_Entity>> getDeptByType(Integer DeptType) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
//                String strSql = "select fd_DeptID,deleted,fd_DeptName,fd_DeptType,fd_ModifiedDate,fd_CompanyCode from dbo.t_DeptInfo where fd_DeptType = "+ DeptType +"' ";
//                return entityManager.createNativeQuery(strSql, DeptInfo_T_Entity.class).getResultList();
                Query query =  entityManager.createQuery("select d from DeptInfo_T_Entity d where d.fdDeptType = :DeptType and d.deleted = 0", DeptInfo_T_Entity.class).setParameter("DeptType", DeptType);
                return query.getResultList();
            });
        }, executionContext);
    }


}